<?php
/**
 * Created by PhpStorm.
 * User: geminiblue
 * Date: 14-3-3
 * Time: 上午10:05
 */

class OrderController extends UController
{
    public function init()
    {
        parent::init();
    }

    /**
     * 跳转至银行充值页面
     */
    public function actionaffirmredirect()
    {
        $data        = array('success'=>0,'msg'=>'');
        $projectId   = $this->_post('projectId');
        $projectName = $this->_post('projectName');
        $payNeeded   = $this->_post('payneeded');
        $bank_id     = $this->_post('bank_id',null);
        $banks = Yii::app()->params['mobileBanks'];
        $usableIds = array();
        foreach($banks as $b)
        {
            $usableIds[] = $b['code'];
        }
        if(!in_array($bank_id, $usableIds))
            $data['msg'] = '暂不支持该银行支付';
        elseif(!$payNeeded || $payNeeded<=0)
            $data['msg'] = '支付金额必须大于0';
        else
        {
            $pay_method = $this->_post('pay_method');
            $result     = $this->saveOrder($bank_id,$pay_method);
            if($result && $result->success && $result->result->tradeNo)
            {
                $data["tradeNo"]      = $result->result->tradeNo;
                $data['success']      = 1;
                $data['msg']          = "ok";
            }
            else
                $data['msg']    = $result->errorMsg;
        }
        $this->setResult($data);
    }

    /**
     * 保存订单
     * pay_method: 0：余额支付 3：连连支付,1：易生，2：盛富通
     * @return mixed|null
     */
    private function saveOrder($bank_id='',$pay_method = '0')
    {
        $model       = User::model();
        $user        = $model->findById($this->userId);
        $password    = $this->_post('password');
        if(!$model->checkPayPass($this->userId,$password))
        {
            return (object)array('errorMsg'=>'交易密码不正确','success'=>0);
        }
        if(!in_array($pay_method, array(0,3)))
        {
            return (object)array('errorMsg'=>'暂不支持该支付方式','success'=>0);
        }
        $cap         = $this->_post('cap',0);//余额支付金额
        $rab         = $this->_post('rab',0);//红包使用金额
        $projectId   = $this->_post('projectId');
        $projectName = $this->_post('projectName');
        $amount      = $this->_post('amount'); //投资金额
        $pay_amount  = $this->_post('payneeded',0);//第三方支付金额
        $card_number = $this->_post('card_no');//银行卡号
        /*新增投资券功能*/
        $used_coupon_amount = $this->_post('couponAmount',0);//投资券金额
        $coupon_max = Yii::app()->params['couponUseLimit'];
        if($used_coupon_amount>$coupon_max)
        {
            return (object)array('errorMsg'=>'一次投资最多可使用'.$coupon_max.'元现金券','success'=>0);
        }
        $coupon_ids         = $this->_post('coupons','');//投资券id 多个以:分隔
        if($used_coupon_amount==0)
            $coupon_ids='';
        $annual_id  = $this->_post('annual_id',0);//年化券id
        //订单来源
        $order_from = $this->_post('order_from');//订单来源 1:android 2:ios
        $projectBalance = Project::model()->getBalance($projectId);
        if(in_array($pay_method, array(3,5)))
        {
            $maxAmount = Helper::getMaxPayAmount($bank_id,$pay_method);
            if($pay_amount > $maxAmount*10000)
            {
                return (object)array('errorMsg'=>'该银行卡单笔最高可支付'.($maxAmount>=1?$maxAmount.'万':10000*$maxAmount).'元','success'=>0);
            }
        }
        if($amount > $projectBalance)
        {
            return (object)array('errorMsg'=>'投资金额不能大于项目可投金额','success'=>0);
        }
        if(!in_array($order_from, array(1,2)))
        {
            return (object)array('errorMsg'=>'order_from参数不合法','success'=>0);
        }
        if(SITEMODE !== 'DEVELOP' && $cap+$rab+$used_coupon_amount+$pay_amount != $amount)
        {
            return (object)array('errorMsg'=>'支付总额不等于投资金额','success'=>0);
        }
        if($pay_method!=0 && $pay_amount==0)
        {
            return (object)array('errorMsg'=>'手机充值业务正在维护中','success'=>0);
        }
        $bank_code = '';
        if($bank_id)
        {
            $banks = Yii::app()->params['mobileBanks'];
            foreach($banks as $b)
            {
                if($b['code'] == $bank_id)
                {
                    $bank_code = $b['alias'];
                    break;
                }
            }
        }
        $data = array(
            'user_id'            => $this->userId,
            'username'           => $user->mobile,
            'project_id'         => $projectId,
            'project_name'       => $projectName,
            'invest_amount'      => $amount,
            'method'             => ($pay_amount==0)?0:$pay_method,
            'notice'             => '',
            'bank_code'          => $bank_code,
            'used_capital'       => $cap,
            'used_reward'        => $rab,
            'pay_amount'         => $pay_amount,
            'used_coupon_amount' => $used_coupon_amount,
            'coupon_ids'         => $coupon_ids,
            'order_from'         => $order_from,
            'annual_id'          => $annual_id,
            'card_no'            => $card_number,
        );
        $result = HttpLib::post($this->javaApi['create_order'],$data);
        Helper::positionRecord('order',$this->userId);
        return $result;
    }
    /**
     * 直接交易页面（余额支付）
     */
    public function actionaffirmdo()
    {
        $projectId = $this->_post('projectId');
        $projectName = $this->_post('projectName');
        $data = array(
            'code'        => 500,
            'success'     => 0,
            'errcode'     => 0,
            'msg'         => null,
            'projectId'   => $projectId,
            'projectName' => $projectName,
            'praise'      => 0, //是否好评
        );
        $t = $this->saveOrder('',0);
        if($t && $t->success && $t->result->tradeNo)
        {
            $result = HttpLib::post($this->javaApi['do_transaction'],array(
                'trade_no' => $t->result->tradeNo,
                'user_id'  => $this->userId,
                'token'    => $this->token,
            ));
            if($result && $result->success)
            {
                $remote = HttpLib::get($this->javaApi['pay_invest_over'],array(
                            'trade_no' => $t->result->tradeNo,
                            'user_id'  => $this->userId,
                            'token'    => $this->token,
                ));
                if($remote->result->success)
                {
                    $data['code']         = 200;
                    $data['success']      = 1;
                    $data['projectName']  = $remote->result->projectName;
                    $data['investAmount'] = $remote->result->investAmount;
                    $data['paying']       = 0;
                    $data['praise']       = Helper::getPraise($this->userId);
                }
                elseif($remote->result->code == 20528)
                {
                    $data['code']         = 200;
                    $data['success']      = 1;
                    $data['projectName']  = $remote->result->projectName;
                    $data['investAmount'] = $remote->result->investAmount;
                    $data['paying']       = 1;//支付中
                    $data['praise']       = Helper::getPraise($this->userId);
                }
                else
                {
                    $data['errcode'] = $remote->result->code;
                    $data['msg']     = $remote->result->errorMsg;
                    if(in_array($remote->code,array('20802','20803','20804','20805')))
                    {
                        $data['msg'] = '投资劵使用失败，请重新投资';
                    }
                }

                if(MOBILEOS === 'ios' && $data['success']==1)
                {
                    $info   = User::model()->findById($this->userId);
                    $mobile = $info->mobile;
                    Helper::pushIFA($mobile,'transaction',$remote->result->investAmount);
                }
            }
            else
            {
                $data['errcode'] = $result->code;
                $data['msg']     = $result->errorMsg;
            }
        }
        else
        {
            $data['errcode'] = $t->code;
            $data['success'] = 0;
            $data['msg']     = $t->errorMsg;
        }
        $this->setResult($data);
    }
    /**
     * 第三方支付状态(第三方支付完成后调用)
     */
    public function actionPayStatus()
    {
        $data  = array('success'=>0,'praise'=>0);
        $tradeNo = $this->_post('tradeNo',null);
        if($tradeNo === null)
            $data['msg'] = 'illegal request param';
        else
        {
            $remote = HttpLib::get($this->javaApi['pay_invest_over'],array(
                          'trade_no'=> $tradeNo,
                          'user_id'=>$this->userId
            ));
            if($remote->result->success)
            {
                $data['msg']     = 'ok';
                $data['success'] = 1;
                $data['paying']  = 0;
                $data['praise']  = Helper::getPraise($this->userId);
            }
            elseif($remote->result->code == 20528)//处理队列处理中
            {
                $data['msg']     = '提交成功，处理中...';
                $data['success'] = 1;
                $data['paying']  = 1;
            }
            else
                $data['msg'] =  $remote->result->errorMsg;
            if(MOBILEOS === 'ios' && $data['success']==1)
            {
                $info   = User::model()->findById($this->userId);
                $mobile = $info->mobile;
                Helper::pushIFA($mobile,'transaction',$remote->result->investAmount);
            }
        }
        $this->setResult($data);
    }
}
